﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HCFramework.API.LINQ;

namespace HCFramework.Control.News
{
    public partial class UsrInsertUpdate : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (M.UrlQuery.newsID.HasValue)
                {
                    ButtonAdd.Visible = false;
                    ButtonUpdate.Visible = true;

                    // Bind edit form
                    New n = C.NewsController.GetByID(M.UrlQuery.newsID.Value);
                    cboLang.ClearSelection();
                    cboLang.SelectedValue = n.DisplayInLang;
                    txtTitle.Text = n.Title;
                    txtSummary.Text = n.Summary;
                    RadEditor1.Content = n.Content;
                }
            }
        }

        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            // Insert a record
            New n = new New();
            n.DisplayInLang = cboLang.SelectedValue;
            n.Title = txtTitle.Text;
            n.Summary = txtSummary.Text;
            n.Content = RadEditor1.Content;
            //n.TrangID = C.TrangController.GetCurrentTrangOrInsert().TrangID;
            n.UserIdCreated = C.UserController.GetCurrentUser().UserID;
            C.NewsController.Insert(n);

            // Clear form
            ClearForm();

            // Refresh page
            M.Common.Refresh();
        }

        private void ClearForm()
        {
            txtTitle.Text = "";
            txtSummary.Text = "";
            RadEditor1.Content = "";
        }

        protected void ButtonUpdate_Click(object sender, EventArgs e)
        {
            // Update
            HCDataContext db = new HCDataContext();
            New n = C.NewsController.GetByID(M.UrlQuery.newsID.Value, db);
            n.DisplayInLang = cboLang.SelectedValue;
            n.Title = txtTitle.Text;
            n.Summary = txtSummary.Text;
            n.Content = RadEditor1.Content;
            C.NewsController.Update(n, db);

            // Clear form
            ClearForm();

            // Refresh
            M.Common.Refresh();
        }
    }
}